package com.jsgt.greekfire.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.fhx.core.AppContext
import com.fhx.core.base.BaseViewModel
import com.jsgt.greekfire.common.util.MD5Util
import com.fhx.core.utils.ToastUtils
import com.jsgt.jni.JniUtil
import com.jsgt.greekfire.bean.*
import com.jsgt.greekfire.common.http.ResponseData
import com.jsgt.greekfire.common.http.safeLaunch
import com.jsgt.greekfire.repository.UserRepository
import retrofit2.http.POST
import java.math.BigInteger

/**
 * author fhx
 * create time 2020/4/25 20:56
 * 绑定的Activity,Fragment一旦走了onDestroy之后，ViewMode就发不出网络请求了。所以使用Fragment时要注意
 **/
class UserViewModel() : BaseViewModel() {
    val userRepository = UserRepository.instance
    val errorLiveData by lazy { MutableLiveData<Any>() }
    val userInfoLiveData by lazy { MutableLiveData<UserBean>() }
    val noticeListLiveData by lazy { MutableLiveData<List<MessageBean>>() }
    val msgListLiveData by lazy { MutableLiveData<List<MessageBean>>() }
    val msgInfoLiveData by lazy { MutableLiveData<MessageBean>() }
    val sendSmsLiveData by lazy { MutableLiveData<Any>() }
    val sendEmailLiveData by lazy { MutableLiveData<Any>() }
    val checkSMSLiveData by lazy { MutableLiveData<Any>() }
    val checkEmailLiveData by lazy { MutableLiveData<Any>() }
    val updateTradingPwdLiveData by lazy { MutableLiveData<Any>() }
    val updateSecurityPwdLiveData by lazy { MutableLiveData<String>() }
    val valuationCoinListLiveData by lazy { MutableLiveData<List<Any>>() }
    val updateValuationCoinLiveData by lazy { MutableLiveData<Any>() }
    val bindPhoneLiveData by lazy { MutableLiveData<Any>() }
    val bindEmailLiveData by lazy { MutableLiveData<Any>() }
    val activityTransferLiveData by lazy { MutableLiveData<Any>() }
    val activityTransfer2LiveData by lazy { MutableLiveData<Any>() }
    val activityTransferList by lazy { MutableLiveData<List<TransferBean>>() }
    val getPrice by lazy { MutableLiveData<GetPrice>() }
    val myCoinNumberLiveData by lazy { MutableLiveData<MinerBean>() }
    val totalCoinNumberLiveData by lazy { MutableLiveData<String>() }
    val coinPoolListLiveData by lazy { MutableLiveData<List<MinerBean>>() }
    val searchMinerListLiveData by lazy { MutableLiveData<List<MinerBean>>() }

    //val assetsListLiveData = MutableLiveData<List<AssetsBean>>()
    val assetsManageListLiveData by lazy { MutableLiveData<List<AssetsBean>>() }
    val addressAddLiveData by lazy { MutableLiveData<String>() }
    val addressListLiveData by lazy { MutableLiveData<List<AddressBean>>() }
    val poolDataLiveData by lazy { MutableLiveData<IncomeBean>() }
    val versionUpdateLiveData by lazy { MutableLiveData<UpdateBean>() }
    val coinBillLiveData by lazy { MutableLiveData<List<BillBean>>() }
    val withdrawLiveData by lazy { MutableLiveData<List<BillBean>>() }
    val minerTotalLiveData by lazy { MutableLiveData<Int>() }
    val tradingRecordLiveData by lazy { MutableLiveData<List<BillBean>>() }
    val teamDeviceNumLiveData by lazy { MutableLiveData<Int>() }
    val directPushNumLiveData by lazy { MutableLiveData<Int>() }
    val logoutLiveData by lazy { MutableLiveData<Any>() }
    val poolActBoolean by lazy { MutableLiveData<Int>() }
    val genesisActBoolean by lazy { MutableLiveData<Int>() }

    //****************ATR*****************************
    val getAccountLiveData by lazy { MutableLiveData<AtrAccountInfoBean>() }
    val transferLiveData by lazy { MutableLiveData<TransferResult>() }
    val tradeOrderPageLiveData by lazy { MutableLiveData<TradeOrderPage>() }
    val versionLiveData by lazy { MutableLiveData<Version>() }

    /**
     * 获取地址信息
     */
    fun getAccount(address: String, visible: String) {
        val params = HashMap<String, Any>()
        params["address"] = address
        params["visible"] = visible
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.getAccount(params)
                getAccountLiveData.value = data
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 创建一笔转账Transaction
     */
    fun transfer(fromAddress: String, toAddress: String, amount: BigInteger, visible: String) {
        val params =
            "{\"owner_address\":\"${fromAddress}\",\"to_address\":\"${toAddress}\",\"amount\":${amount},\"visible\":\"${visible}\"}"

        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.transfer(params)
                transferLiveData.value = data
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 交易列表
     */
    fun getTradeOrderList(address: String, contractType: String?, start: String, limit: String) {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.getTradeOrderList(address, contractType, start, limit)
                tradeOrderPageLiveData.value = data
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 获取版本更新
     */
    fun getVersion() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.getVersion()
                if (data.code == 0) {
                    if (versionLiveData.value == null || versionLiveData.value?.version != data.result?.version) {
                        versionLiveData.value = data.result
                    }
                } else {
                    errorLiveData.value = data.msg
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }


    /**
     * 最新公告
     */
    fun noticeList(page: Int, limit: Int) {
        viewModelScope.safeLaunch {
            val params = HashMap<String, Any>()
            params["page"] = page
            params["limit"] = limit
            block = {
                val data = userRepository.noticeList(params)
                if (data.code == 0) {
                    noticeListLiveData.value = data.result?.list
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    //------------以上ATR---------------------
    /**
     * 用户信息
     */
    fun userInfo() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.userInfo()
                if (data.code == 0) {
                    userInfoLiveData.value = data.userInfo
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 矿池活动是否开启
     */
    fun poolActIsStart() {
        viewModelScope.safeLaunch {
            block = {
                val datas = userRepository.poolActiveIsStart()
                if (datas.code == 0) {
                    if (datas.data is String) {
                        poolActBoolean.value = datas.data.toInt();
                    }
                } else {
                    errorLiveData.value = datas;
                }
            }
            onError = {
                errorLiveData.value = it.message;
            }
        }
    }

    /**
     * 创世区块是否开启
     */
    fun genesisActIsStart() {
        viewModelScope.safeLaunch {
            block = {
                val datas = userRepository.genesisActiveIsStart()
                if (datas.code == 0) {
                    if (datas.data is String) {
                        genesisActBoolean.value = datas.data.toInt();
                    }
                } else {
                    errorLiveData.value = datas;
                }
            }
            onError = {
                errorLiveData.value = it.message;
            }
        }
    }

    /**
     * 消息列表
     */
    fun messageList() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.messageList()
                if (data.code == 0) {
                    msgListLiveData.value = data.result
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 消息详情
     */
    fun messageInfo() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.messageInfo()
                if (data.code == 0) {
                    msgInfoLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 发送短信
     */
    fun sendSMS(phoneNumber: String) {
        viewModelScope.safeLaunch {
            block = {
                val data =
                    userRepository.sendSMS(phoneNumber, JniUtil.getSignKeyPwd(phoneNumber))
                if (data.code == 0) {
                    sendSmsLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 发送邮箱
     */
    fun sendEmail(email: String) {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.sendEmail(email, JniUtil.getSignKeyPwd(email))
                if (data.code == 0) {
                    sendEmailLiveData.value = data.msg
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 验证短信码
     */
    fun checkSMSCode(phone: String, code: String) {
        val params = HashMap<String, Any>()
        params["phone"] = phone
        params["kaptcha"] = code
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.checkSMSCode(params)
                if (data.code == 0) {
                    checkSMSLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 验证邮箱码
     */
    fun checkEmailCode(email: String, code: String) {
        val params = HashMap<String, Any>()
        params["email"] = email
        params["kaptcha"] = code
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.checkEmailCode(params)
                if (data.code == 0) {
                    checkEmailLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 修改交易密码
     */
    fun updateTradingPwd(tradingPwd: String) {
        val params = HashMap<String, Any>()
        params["payPassword"] = MD5Util.getMD5(tradingPwd)
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.updateTradingPwd(params)
                if (data.code == 0) {
                    updateTradingPwdLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 修改安全密码
     */
    fun updateSecurityPwd(oldPwd: String, securityPassword: String) {
        val params = HashMap<String, Any>()
        params["securityPassword"] = MD5Util.getMD5(securityPassword)
        params["oldSecurityPassword"] = MD5Util.getMD5(oldPwd)
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.updateSecurityPwd(params)
                if (data.code == 0) {
                    updateSecurityPwdLiveData.value = data.msg
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 计价货币列表
     */
    fun valuationCoinList() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.valuationCoinList()
                if (data.code == 0) {
                    valuationCoinListLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 修改计价货币
     */
    fun updateValuationCoin(guid: String, valuationCurrencyId: String) {
        val params = HashMap<String, Any>()
        params["guid"] = guid
        params["valuationCurrencyId"] = valuationCurrencyId
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.updateValuationCoin(params)
                if (data.code == 0) {
                    updateValuationCoinLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 绑定手机
     */
    fun bindPhone(mobile: String) {
        val params = HashMap<String, Any>()
        params["mobile"] = mobile
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.bindPhone(params)
                if (data.code == 0) {
                    bindPhoneLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 更改手机
     */
    fun modifyPhone(mobile: String, oldMobile: String) {
        val params = HashMap<String, Any>()
        params["mobile"] = mobile
        params["oldMobile"] = oldMobile
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.modifyPhone(params)
                if (data.code == 0) {
                    bindPhoneLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 绑定邮箱
     */
    fun bindEmail(email: String) {
        val params = HashMap<String, Any>()
        params["email"] = email
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.bindEmail(params)
                if (data.code == 0) {
                    bindEmailLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 更改邮箱
     */
    fun editEmail(email: String, oldEmail: String) {
        val params = HashMap<String, Any>()
        params["email"] = email
        params["oldEmail"] = oldEmail
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.editEmail(params)
                if (data.code == 0) {
                    bindEmailLiveData.value = data.data
                } else {
                    ToastUtils.show(data.msg!!)
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 转账激活
     */
    fun activityTransfer(
        address: String, amount: String,
        payPassword: String
    ) {
        val params = HashMap<String, Any>()
        params["address"] = address
        params["amount"] = amount
        params["payPassword"] = MD5Util.getMD5(payPassword)
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.activityTransfer(params)
                if (data.code == 0) {
                    activityTransferLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 确定激活
     */
    fun activityTransfer2(guid: String) {
        val params = HashMap<String, Any>()
        params["guid"] = guid
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.activityTransfer2(params)
                if (data.code == 0) {
                    activityTransfer2LiveData.value = data.data
                } else {
                    ToastUtils.show(data.msg!!)
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 确定激活列表
     */
    fun activityTransferList() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.activityTransferList()
                if (data.code == 0) {
                    activityTransferList.value = data.result
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 查询币种价格
     * api/gfcmarket/getPrice
     */
    fun getPrice() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.getPrice()
                if (data.code == 0) {
                    getPrice.value = data.data
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }


    /**
     * 查询持币
     */
    fun myCoinNumber() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.myCoinNumber()
                if (data.code == 0) {
                    myCoinNumberLiveData.value = data.userPerformance
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(AppContext.instance, data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 全网总产出
     */
    fun totalCoinNumber() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.totalCoinNumber()
                if (data.code == 0) {
                    totalCoinNumberLiveData.value = data.result
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 矿工列表
     */
    fun coinPoolList(page: Int, size: Int) {
        val params = HashMap<String, Any>()
        params["page"] = page.toString()
        params["limit"] = size.toString()
        params["userName"] = ""
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.coinPoolList(params)
                if (data.code == 0) {
                    coinPoolListLiveData.value = data.result?.list
                    if (data.me == null) {
                        minerTotalLiveData.value = 0
                        teamDeviceNumLiveData.value = 0
                        directPushNumLiveData.value = 0
                    } else {
                        minerTotalLiveData.value = data.me.teamNum!!.toInt()//总矿工
                        teamDeviceNumLiveData.value = data.me.teamDeviceNum!!.toInt()//总设备数量
                        directPushNumLiveData.value = data.me.directPushNum!!.toInt()//直推人数
                    }
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(AppContext.instance, data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 搜索矿工
     */
    fun searchMinerList(userName: String, page: Int, size: Int) {
        val params = HashMap<String, Any>()
        params["page"] = page.toString()
        params["limit"] = size.toString()
        params["userName"] = userName
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.coinPoolList(params)
                if (data.code == 0) {
                    searchMinerListLiveData.value = data.result?.list
                } else {
                    errorLiveData.value = data
                    ToastUtils.show(AppContext.instance, data.msg!!)
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 资产列表
     */
    /*fun userAssetList() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.userAssetList()
                if (data.code == 0) {
                    assetsListLiveData.value = data.list
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }*/

    /**
     * 资产管理列表
     */
    fun userAssetManageList() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.userAssetManageList()
                if (data.code == 0) {
                    assetsManageListLiveData.value = data.list
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 添加联系人
     */
    fun addAddress(
        assetTypeId: String,
        assetTypeName: String,
        contactName: String,
        contactRemark: String,
        addr: String
    ) {
        val params = HashMap<String, Any>()
        params["assetTypeId"] = assetTypeId
        params["assetTypeName"] = assetTypeName
        params["contactName"] = contactName
        params["addr"] = addr
        params["contactRemark"] = contactRemark
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.addAddress(params)
                if (data.code == 0) {
                    addressAddLiveData.value = data.msg
                } else {
                    ToastUtils.show(data.msg!!)
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 地址簿
     */
    fun addressList(assetTypeId: String) {
        val params = HashMap<String, Any>()
        params["assetTypeId"] = assetTypeId
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.addressList(params)
                if (data.code == 0) {
                    addressListLiveData.value = data.list
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 币币账单
     */
    fun assetsLogList(assetGuid: String, assetEvent: String, page: Int, size: Int) {
        val params = HashMap<String, Any>()
        params["assetGuid"] = assetGuid
        params["assetEvent"] = assetEvent
        params["page"] = page.toString()
        params["limit"] = size.toString()
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.assetsLogList(params)
                if (data.code == 0) {
                    coinBillLiveData.value = data.list
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 充币账单
     */
    fun rechargeLogList(assetGuid: String, assetEvent: String, page: Int, size: Int) {
        val params = HashMap<String, Any>()
        params["assetGuid"] = assetGuid
        params["assetEvent"] = assetEvent
        params["page"] = page.toString()
        params["limit"] = size.toString()
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.rechargeLogList(params)
                if (data.code == 0) {
                    coinBillLiveData.value = data.data
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 提币记录
     */
    fun withdrawRecord(page: Int, size: Int, assetTypeId: Int) {
        val params = HashMap<String, Any>()
        params["page"] = page.toString()
        params["limit"] = size.toString()
        params["assetTypeId"] = assetTypeId.toString()
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.withdrawRecord(params)
                if (data.code == 0) {
                    withdrawLiveData.value = data.result?.list
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 交易记录
     */
    fun tradingRecord(assetGuid: String, logType: String, page: Int, size: Int) {
        val params = HashMap<String, Any>()
        params["assetGuid"] = assetGuid
        params["logType"] = logType
        params["page"] = page.toString()
        params["limit"] = size.toString()
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.assetsLogList(params)
                if (data.code == 0) {
                    tradingRecordLiveData.value = data.list
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                ToastUtils.show(it.message!!)
                errorLiveData.value = it.message
            }
        }
    }


    /**
     * 矿池算力数据
     */
    fun poolData() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.poolData()
                if (data.code == 0) {
                    poolDataLiveData.value = data.result
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 版本更新
     */
    fun getAppVersion() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.getAppVersion()
                if (data.code == 0) {
                    versionUpdateLiveData.value = data.result
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 退出登录
     */
    fun logout() {
        viewModelScope.safeLaunch {
            block = {
                val data = userRepository.logout()
                if (data.code == 0) {
                    logoutLiveData.value = data.msg
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }
}